<template>
  <div>
    <div class="setting">
      <!-- <p class="mb-6">基本设置</p> -->
      <div>
        <div class="flex jcsb">
          <div class="setting-box" style="width: 49.3%">
            <p class="setting-title">
              安全配置
              <!-- <span class="font-bold" @click="getStrategybuilders()">刷新</span> -->
            </p>
            <el-form :rules="securityRules" class="security-config" ref="securityConfigRef" :model="securityConfig" label-width="180px">
              <el-form-item label="系统强制登出时间" prop="timeOut"> <el-input style="width: 200px" v-model.number="securityConfig.timeOut" /><span class="tip-text">登出时间在5-30分钟</span> </el-form-item>
              <el-form-item label="可尝试登录次数" prop="loginNum"> <el-input style="width: 200px" v-model.number="securityConfig.loginNum" /><span class="tip-text">登录次数在3-5次</span> </el-form-item>
              <el-form-item label="密码最小长度设置" prop="passwordLength"> <el-input style="width: 200px" v-model.number="securityConfig.passwordLength" /><span class="tip-text">最大长度为25位</span> </el-form-item>
              <!-- <el-form-item label="IP访问限制白名单" prop="ip"> <el-input style="width: 200px" v-model="securityConfig.ip" /><span class="tip-text">正确的IP地址格式为 x.x.x.x/x</span> </el-form-item> -->
              <!-- <el-form-item label="MAC访问限制白名单" prop="mac"> <el-input style="width: 200px" v-model="securityConfig.mac" /><span class="tip-text">正确的Mac地址格式为 xx:xx:xx:xx:xx:xx</span> </el-form-item> -->
              <!-- <el-form-item label="禁止远程管理"> <el-switch v-model="securityConfig.remote" /><span class="tip-text">当启用禁止远程管理之后,所有人都将无法登录。</span> </el-form-item> -->
              <!--                        <el-form-item label="Ukey登录验证">-->
              <!--                            <el-switch v-model="securityConfig.Ukey" /><span class="tip-text">Ukey登录验证开启后，所有用户登录需要使用ukey。</span>-->
              <!--                        </el-form-item>-->
              <el-form-item label="密码过期时间(天)" prop="passwordTime"> <el-input style="width: 200px" v-model.number="securityConfig.passwordTime" /><span class="tip-text"></span> </el-form-item>
              <!-- <el-form-item label="日志保存最低月数" prop="logMonth"> <el-input style="width: 200px" v-model.number="securityConfig.logMonth" /><span class="tip-text">日志保存最低月数。（不能低于6个月）</span> </el-form-item> -->
              <el-form-item>
                <el-button type="primary" @click="securityQuery">保存配置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="mt-5 setting-box" style="width: 49.3%">
            <p class="setting-title">
              主题设置
              <!-- <span class="font-bold" @click="getSystemSetting()">刷新</span> -->
            </p>
            <el-form ref="timeRef" :model="themeForm" :rules="timeRules" label-width="180px" style="max-width: 700px">
              <el-form-item label="主题颜色">
                <el-select v-model="themeForm.themeValue" size="large" style="width: 240px" @change="changeTheme">
                  <el-option label="主题1" value="theme1">主题1</el-option>
                  <!-- <el-option label="主题2" value="theme2">主题2</el-option>
                  <el-option label="主题3" value="theme3">主题3</el-option> -->
                  <el-option label="主题4" value="theme4">主题4</el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="菜单风格">
                <el-select v-model="themeForm.layoutValue" size="large" style="width: 240px" @change="collapseFn">
                  <el-option label="详情" :value="false">详情</el-option>
                  <el-option label="简约" :value="true">简约</el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, toRaw, onUnmounted } from 'vue'
import { req_getNetworkInterface, req_getStrategybuilders, req_getSystemSetting, req_setMaxLogin, req_setPort, req_setNtp, req_setSystemTime, req_setSystemTimeCopy } from '~/utils/axios/setting.js'
import { getSysBaseInfo } from '~/utils/axios/login.js'
import moment from 'moment'
import { ElMessage, ElLoading } from 'element-plus'
import { validIp, validMask, validMac } from '~/utils/common/validation.js'
import { Refresh } from '@element-plus/icons-vue'
import { useStorage } from '@vueuse/core'
import { useCollapseStore } from '~/utils/pinia/theme.js'
const collapseStore = useCollapseStore()

/***
 *
 * 主题模块
 *
 * ***/
const themeForm = reactive({
  themeValue: useStorage('theme').value || 'theme1',
  layoutValue: collapseStore.collapse
})
const changeTheme = (theme = 'theme1') => {
  localStorage.setItem('theme', theme)
  document.documentElement.setAttribute('setting-theme', theme)
}
// 菜单栏是否折叠
const collapseFn = val => {
  localStorage.setItem('collapse', val)
  collapseStore.collapse = val
}
// 将 IP 地址转换为长整型
const ipToLong = ip => {
  return ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0
}

// 验证默认网关是否在同一子网中
const isDefaultGatewayInSameSubnet = (rule, value, callback) => {
  const networkAddress = ipToLong(networkForm.ipAddr) & ipToLong(networkForm.netMask)
  const gatewayAddress = ipToLong(value)
  return networkAddress === (gatewayAddress & ipToLong(networkForm.netMask))
}

/***
 *
 * 网络端口配置
 *
 *
 * **/
let networkRef = ref()
let networkForm = reactive({
  portList: [],
  portName: '',
  portStatus: '',
  ipAddr: '',
  netMask: '',
  defaultGW: ''
})
const networkRules = reactive({
  ipAddr: [
    { required: true, message: '请输入正确的IP', trigger: 'change' },
    { validator: validIp, message: '请输入正确的IP', trigger: 'change' }
  ],
  netMask: [
    { required: true, message: '请输入正确的子网掩码', trigger: 'change' },
    {
      validator: validMask,
      message: '请输入正确的子网掩码',
      trigger: 'change'
    }
  ],
  defaultGW: [
    { required: true, message: '请输入正确的默认网关', trigger: 'change' },
    {
      validator: isDefaultGatewayInSameSubnet,
      message: '请输入正确的默认网关',
      trigger: 'change'
    }
  ]
})
const networkQuery = async () => {
  if (!networkRef) return
  await networkRef.value.validate((valid, fields) => {
    if (valid) {
      let networkParams = {
        defaultGW: networkForm.defaultGW,
        ipAddr: networkForm.ipAddr,
        netMask: networkForm.netMask
      }
      req_setPort(networkForm.portName, networkParams).then(res => {
        getNetworkInterface()
      })
    }
  })
}
/***
 *
 *
 * 时钟form表单ref
 *
 * **/
let timeRef = ref()
const timeRules = reactive({
  ntp: [
    { required: true, message: '请输入正确的IP', trigger: 'change' },
    { validator: validIp, message: '请输入正确的IP', trigger: 'change' }
  ]
})
// 时钟同步
let timeForm = reactive({
  timeRadioValue: 1,
  systemTime: '',
  localTime: '',
  ntp: ''
})

const loader = ref(null)
const timeQuery = async () => {
  let ntpParams = {
    activateNtp: true,
    ntpIp: timeForm.ntp
  }
  let systemTimeParams = {
    systemTime: moment(timeForm.systemTime)
      .toISOString()
      .replace(/(\.\d{3})?Z$/, 'Z')
  }
  if (timeForm.timeRadioValue === 0) {
    loader.value = ElLoading.service({
      lock: true,
      text: '系统时间部署中，请稍等...',
      background: 'rgba(0, 0, 0, 0.4)',
      fullscreen: true
    })
    // console.log(loading);
    // fullscreenLoading.value = true
    await req_setSystemTime(systemTimeParams).then(res => {})
    ntpParams.activateNtp = false
  }
  await req_setNtp(ntpParams).then(res => {
    ElMessage({
      message: '配置成功',
      type: 'success'
    })
  })
}
/***
 *
 * 安全配置
 *
 * **/
const securityConfigRef = ref()
const validSecurityIp = (rule, value, callback) => {
  const ipPattern = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}(\/[0-9]{1,2})$/
  return ipPattern.test(value)
}

const securityRules = reactive({
  timeOut: [
    { required: true, message: '登出时间请确认在5-30分钟', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        return value && value >= 5 && value <= 30
      },
      message: '登出时间请确认在5-30分钟',
      trigger: 'change'
    }
  ],
  loginNum: [
    { required: true, message: '登录次数请确认在3-5次', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        return value && value >= 3 && value <= 5
      },
      message: '登录次数请确认在3-5次',
      trigger: 'change'
    }
  ],
  passwordLength: [
    { required: true, message: '密码长度请确认在8-25之间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        return value && value >= 8 && value <= 25
      },
      message: '密码长度请确认在8-25之间',
      trigger: 'change'
    }
  ],
  ip: [
    {
      required: true,
      message: '请输入合法的IP地址格式，如 0.0.0.0/0',
      trigger: 'change'
    },
    {
      validator: validSecurityIp,
      message: '请输入合法的IP地址格式，如 0.0.0.0/0',
      trigger: 'change'
    }
  ],
  mac: [{ validator: validMac, message: '请输入正确的MAC地址', trigger: 'change' }],
  passwordTime: [
    { required: true, message: '密码过期天数在1-30天', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        return value && value >= 1 && value <= 30
      },
      message: '密码过期天数在1-30天',
      trigger: 'change'
    }
  ],
  logMonth: [
    {
      required: true,
      message: '日志保存最低月数必须大于6个月',
      trigger: 'change'
    },
    {
      validator: (rule, value, callback) => {
        return value && value >= 6
      },
      message: '日志保存最低月数必须大于6个月',
      trigger: 'change'
    }
  ]
})
let securityConfig = ref({
  timeOut: '',
  loginNum: '',
  passwordLength: '',
  ip: '',
  mac: '',
  remote: '',
  Ukey: '',
  passwordTime: '',
  logMonth: ''
})
let securityConfigObj = toRefs(securityConfig)
let securityConfigArr = reactive([
  {
    dataName: 'IDLE_TIME',
    oldValue: '',
    value: securityConfigObj.timeOut,
    url: 'idletimestrategyrule'
  },
  {
    dataName: 'MAX_LOGIN_TRY',
    oldValue: '',
    value: securityConfigObj.loginNum,
    url: 'maxlogintrystrategyrule'
  },
  {
    dataName: 'PASSWORD_COMPLEXITY',
    oldValue: '',
    value: securityConfigObj.passwordLength,
    url: 'passwordcomplexitystrategyrule'
  },
  {
    dataName: 'VALID_IP',
    oldValue: '',
    value: securityConfigObj.ip,
    url: 'passwordcomplexitystrategyrule'
  },
  {
    dataName: 'MAC_LOGIN_MANAGEMENT',
    oldValue: '',
    value: securityConfigObj.mac,
    url: 'passwordcomplexitystrategyrule'
  },
  {
    dataName: 'LOGIN_SWITCH',
    oldValue: '',
    value: securityConfigObj.remote,
    url: 'passwordcomplexitystrategyrule'
  },
  {
    dataName: 'UKEY_SWITCH',
    oldValue: '',
    value: securityConfigObj.Ukey,
    url: 'passwordcomplexitystrategyrule'
  },
  {
    dataName: 'PASSWD_EXPIRE',
    oldValue: '',
    value: securityConfigObj.passwordTime,
    url: 'passwordcomplexitystrategyrule'
  },
  {
    dataName: 'LOG_MONTH',
    oldValue: '',
    value: securityConfigObj.logMonth,
    url: 'passwordcomplexitystrategyrule'
  }
])
// 安全配置提交函数
const securityQuery = async () => {
  // 校验表单
  localStorage.setItem('sys-setting', JSON.stringify(securityConfig.value))
  ElMessage.success('保存成功')
}
const setNetworkFormValue = thisPortName => {
  let itemPort = networkForm.portList.filter(item => item.portName == thisPortName)[0]
  networkForm.portName = itemPort.portName
  networkForm.portStatus = itemPort.portStatus
  networkForm.ipAddr = itemPort.ipAddr
  networkForm.netMask = itemPort.netMask
  networkForm.defaultGW = itemPort.defaultGW
}
const getNetworkInterface = () => {
  req_getNetworkInterface().then(res => {
    networkForm.portList = res.data.slotInfoList[0].portInfoList
    setNetworkFormValue(res.data.slotInfoList[0].portInfoList[0].portName)
  })
}
const getStrategybuilders = () => {
  req_getStrategybuilders().then(res => {
    securityConfigArr.map(objData => {
      res.data.map(item => {
        if (objData.dataName == item.strategyRules[0].strategyRuleIdentifier) {
          objData.value = item.strategyRules[0].ruleData
          objData.oldValue = item.strategyRules[0]
          if (objData.dataName == 'LOGIN_SWITCH' || objData.dataName == 'UKEY_SWITCH') {
            objData.value = Boolean(Number(item.strategyRules[0].ruleData))
          }
        }
      })
    })
  })
}
var timeInterval = null
const getSystemSetting = () => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
  req_getSystemSetting().then(res => {
    timeForm.ntp = res.data.ntpIp
    timeForm.timeRadioValue = Number(res.data.activateNtp)
    console.log(timeForm.timeRadioValue)
  })
  getSysBaseInfo().then(res => {
    timeForm.systemTime = moment(res.data).format('YYYY-MM-DD HH:mm:ss')

    timeInterval = setInterval(() => {
      timeForm.systemTime = moment(timeForm.systemTime).add(1, 'seconds').format('YYYY-MM-DD HH:mm:ss')
      timeForm.localTime = moment().format('YYYY-MM-DD HH:mm:ss')
    }, 1000)
  })
}

onMounted(async () => {
  securityConfig.value = JSON.parse(localStorage.getItem('sys-setting')) || {}
  // getNetworkInterface()
  // getStrategybuilders()
  // getSystemSetting()
})
// onUnmounted(() => {
//   loader.value.close()
// })
</script>

<style lang="scss" scoped>
.setting {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  background-color: #fff;
  padding: 24px;
  > p {
    color: #333;
    font-size: 16px;
    font-weight: bold;
  }
}
.basic-box {
  display: inline-block;
  width: 49.4%;
  color: #555;
  overflow: hidden;
  > div {
    padding-bottom: 5px;
    border-radius: 3px;
  }
  :deep(.el-form-item__label) {
    color: rgba(0, 0, 0, 0.65) !important;
  }
}
.basic-box:first-child {
  margin-right: 1rem;
}
.setting-box {
  border: 1px solid #ededed;
}
.setting-title {
  display: flex;
  // width: 100%;
  padding: 0 20px;
  height: 40px;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 20px;
  align-items: center;
  justify-content: space-between;
  background-color: #f0f3f7 !important;
  span {
    cursor: pointer;
  }
}
.online {
  display: inline-block;
  height: 12px;
  width: 12px;
  border-radius: 50%;
  margin-left: 12px;
}
.on-status {
  background-image: linear-gradient(#24ec60 0, #1fe159 100%);
}
.off-status {
  background-image: linear-gradient(#ffb340 0, #ff9900 100%);
}
.tip-text {
  // display: none;
  margin-left: 10px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}
</style>
